<?php

namespace backend\models;

use backend\models\Image;
use backend\models\UserInvite;
use Yii;
use yii\db\ActiveRecord;
use common\models\UserInfo;

/**
 * This is the model class for table "sys_user_designer".
 *
 * @property integer $uid
 * @property string $name
 * @property string $company
 * @property string $address
 * @property string $id_card
 * @property integer $image_idcard_a
 * @property integer $image_idcard_b
 * @property integer $image_bcard
 * @property integer $audit_state
 * @property integer $audit_uid
 * @property integer $audit_time
 * @property string $audit_memo
 * @property integer $apply_time
 */
class SysUserDesigner extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $imageFile_idcard_a, $imageFile_idcard_b, $imageFile_bcard, $province, $city;

    public static function tableName()
    {
        return 'sys_user_designer';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'name', 'company', 'id_card', 'province'], 'required', 'on' => 'create'],
            [['imageFile_idcard_a', 'imageFile_idcard_b'],
                'file',
                'skipOnEmpty' => false,
                'skipOnError' => false,
                'checkExtensionByMimeType' => ['image/gif', 'image/jpeg'],
                'extensions' => ['png', 'jpg'],
                'maxSize' => 1024*1024*1024*6,
                'on' => 'create',
            ],
            [[ 'imageFile_bcard'],
                'file',
                'skipOnEmpty' => true,
                'skipOnError' => false,
                'checkExtensionByMimeType' => ['image/gif', 'image/jpeg'],
                'extensions' => ['png', 'jpg'],
                'maxSize' => 1024*1024*1024*6,
                'on' => 'create',
            ],
            ['id_card', 'match',  'pattern' => '/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/', 'on' => 'create'],
            [['uid'], 'required', 'on' => 'update'],
            [['uid', 'audit_state', 'image_idcard_a', 'image_idcard_b', 'image_bcard', 'audit_uid', 'audit_time'], 'integer'],
            [['name', 'company',], 'string', 'max' => 32],
            [['address'], 'string', 'max' => 128],
            [['audit_memo'], 'string', 'max' => 255],
            [['audit_memo'], 'requiredByASpecial'],
            [['province', 'city', 'apply_time'], 'integer'],
            ['city', 'required', 'when' => function ($model) {
                return !in_array($model->province, ['110000', '120000', '310000', '500000']);
                    }, 'whenClient' => "function (attribute, value) {
                return ['110000', '120000', '310000', '500000'].indexOf($('#sysuserdesigner-province').val()) == -1;
            }"]
        ];
    }

    public function beforeSave($insert)
    {
        $this->apply_time = strtotime('now');
        return true;
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['create'] = ['uid', 'name', 'company', 'id_card', 'province', 'city', 'imageFile_idcard_a', 'imageFile_idcard_b', 'imageFile_bcard'];
        $scenarios['update'] = ['uid', 'audit_memo'];
        return $scenarios;
    }

    public function valiCity()
    {
        if (empty($this->province) || !in_array($this->province, ['110000', '120000', '310000', '500000'])) {
            if ($this->city == '') {
                $this->addError('city', '城市不能为空');
            }
        }
    }

    public function getTime0()
    {
        return $this->hasOne(UserPayVip::className(), ['user_id' => 'uid']);
    }

    public function getTel0()
    {
        return $this->hasOne(UserInfo::className(), ['id' => 'uid']);
    }

    public function getInvite()
    {
        return $this->hasOne(UserInvite::className(), ['uid' => 'uid']);
    }

    public function getUserinfo()
    {
        return $this->hasOne(UserInfo::className(), ['id' => 'uid']);
    }

    public function upload()
    {
        $a_dir = $this::genAddr('id_card');
        $b_dir = $this::genAddr('id_card');
        isset($this->imageFile_bcard) ? $c_dir = $this::genAddr('card') : '';
        //生成目录
        if (mkdir($a_dir['path'] . $a_dir['dir'], 0777, true)
            && mkdir($b_dir['path'] . $b_dir['dir'], 0777, true)
            && (empty($this->imageFile_bcard) || mkdir($c_dir['path'] . $c_dir['dir'], 0777, true))
           )
        {

            $full_path_a = $a_dir['path'] . $a_dir['dir'] . $a_dir['name'] . '.' . $this->imageFile_idcard_a->extension;
            $full_path_b = $b_dir['path'] . $b_dir['dir'] . $b_dir['name'] . '.' . $this->imageFile_idcard_b->extension;
            isset($this->imageFile_bcard) ? $full_path_c = $c_dir['path'] . $c_dir['dir'] . $c_dir['name'] . '.' . $this->imageFile_bcard->extension : '';

            //保存图片
            $this->imageFile_idcard_a->saveAs($full_path_a);
            $this->changeImgSize($full_path_a); //改变图片大小
            $img_info_a = getimagesize($full_path_a); //获取图片尺寸


            $this->imageFile_idcard_b->saveAs($full_path_b);
            $this->changeImgSize($full_path_b);
            $img_info_b = getimagesize($full_path_b);

            if (isset($this->imageFile_bcard)) {
                $this->imageFile_bcard->saveAs($full_path_c);
                $this->changeImgSize($full_path_c);
                $img_info_c = getimagesize($full_path_c);
            }

            //传输到正式服
            if (self::transportImg($a_dir['dir'], $a_dir['name'], $this->imageFile_idcard_a->extension, $full_path_a)
                && self::transportImg($b_dir['dir'], $b_dir['name'], $this->imageFile_idcard_b->extension, $full_path_b)
                && (empty($this->imageFile_bcard) || self::transportImg($c_dir['dir'], $c_dir['name'], $this->imageFile_bcard->extension, $full_path_c))
               )
            {
                //保存图片到数据库
                $this->image_idcard_a = self::saveImg('id_card', $a_dir['dir'] . $a_dir['name'] . '.' . $this->imageFile_idcard_a->extension, $img_info_a);
                $this->image_idcard_b = self::saveImg('id_card', $b_dir['dir'] . $b_dir['name'] . '.' . $this->imageFile_idcard_b->extension, $img_info_b);
                isset($this->imageFile_bcard) ? $this->image_bcard = self::saveImg('card', $c_dir['dir'] . $c_dir['name'] . '.' . $this->imageFile_bcard->extension, $img_info_c) : '';

                if ($this->image_idcard_a && $this->image_idcard_b && (empty($this->imageFile_bcard) || $this->image_bcard)) {
                    empty($this->imageFile_bcard) ? $this->image_bcard = 0 : '';
                    return true;
                } else {
                    //保存数据库失败
                    return false;
                }
            } else {
                // "传输出错";
                return false;
            }
        } else {
            //echo "创建目录失败";
            return false;
        }
    }

    //改变上传图片的大小
    function changeImgSize($fullPath)
    {
        $imgInfo = getimagesize($fullPath);
        if ($imgInfo[0] > 500 || $imgInfo[1] > 500) {
            if ($imgInfo[0] > 500) {
                $newwidth = 500;
                $newheight = $imgInfo[1] * 500 / $imgInfo[0];
            }
            if ($imgInfo[1] > 500) {
                $newheight = 500;
                $newwidth = $imgInfo[0] * 500 / $imgInfo[1];
            }

            $thumb = imagecreatetruecolor($newwidth, $newheight);
            if ($imgInfo[2] == 2) {
                $source = imagecreatefromjpeg($fullPath);
            } elseif ($imgInfo[2] == 3) {
                $source = imagecreatefrompng($fullPath);
            }
            imagecopyresized($thumb, $source, 0, 0, 0, 0, floor($newwidth), floor($newheight), $imgInfo[0], $imgInfo[1]);
            switch ($imgInfo[2]) {
                //支持jpg
                case 2:
                    imagejpeg($thumb, $fullPath);
                    break;
                //支持png
                case 3:
                    imagepng($thumb, $fullPath);
                    break;
                default:
                    echo "<script>alert('待开发其他类型');</script>";
                    break;
            }
        }
    }


    //传输图片到正式服
    public static function transportImg($dir, $name, $imgType, $imgFullPath)
    {
        $url = "https://app.jajahome.com/furniture/calc.php";
        if (class_exists('\CURLFile')) {
            $post_data = [
                "q" => "uploadImg",
                "dir" => $dir,
                "name" => $name,
                "file_type" => $imgType,
                "img" => new \CURLFile($imgFullPath)
            ];
        } else {
            $post_data = [
                "q" => "uploadImg",
                "dir" => $dir,
                "name" => $name,
                "file_type" => $imgType,
                "img" => "@" . realpath($imgFullPath)
            ];
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        $errorCode = curl_errno($ch);
        curl_close($ch);
        return $output == "done";

    }

    public static function saveImg($type, $path, $info)
    {
        $a = [
            "id_card" => [
                'id' => 190,
                'name' => '身份证'
            ],
            'card' => [
                'id' => 191,
                'name' => '名片'
            ]
        ];
        $image = new Image();
        $image->type = $a[$type]['id'];
        $image->url = $path;
        $image->name = $a[$type]['name'];
        $image->width = $info[0];
        $image->height = $info[1];
        $image->update_time = strtotime('now');
        if ($image->save()) {
            return Yii::$app->db->getLastInsertID();
        } else {
            return false;
        }
    }

    public function concatAddress()
    {
        if ($this->province == null) {
            return false;
        }
        if ($this->city) {
            $t = ActiveRecord::findBySql('SELECT group_concat(`name` SEPARATOR" ") AS `name` FROM grp_city WHERE id IN (' . $this->province . ',' . $this->city . ')')->asArray()->all();
        } else {
            $t = ActiveRecord::findBySql('SELECT group_concat(`name` SEPARATOR" ") AS `name` FROM grp_city WHERE id IN (' . $this->province . ')')->asArray()->all();
        }
        $this->address = $t[0]['name'];
        return true;
    }

    //生成身份证和名片目录,参数："id_card"或"card"
    public static function genAddr($type)
    {
        $a = [
            "id_card" => 190,
            'card' => 191
        ];
        $result = PrfType::find()->where(['id' => $a[$type]])->one();
        $uuid = md5(uniqid());
        $uuid_a = substr($uuid, 0, 3);
        $uuid_b = substr($uuid, 3, 3);
        $uuid_c = substr($uuid, 6, 3);
        $uuid_d = substr($uuid, 9, 3);
        $dir = 'images/' . $result->addr . '/' . $uuid_a . '/' . $uuid_b . '/' . $uuid_c . '/' . $uuid_d . '/';
        $name = substr($uuid, 12, 20);
        $path = '../../backend/web/';
        return [
            'path' => $path,
            "dir" => $dir,
            "name" => $name
        ];
    }

    public function requiredByASpecial($attribute, $params)
    {
        if ($this->audit_state == 2) //审核失败
        {
            if ($this->audit_memo == '')
                $this->addError($attribute, "审核失败时，原因不能为空");
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'uid' => '用户ID',
            'name' => Yii::t('app', 'Designer Name'),
            'company' => Yii::t('app', 'Designer Company'),
            'address' => Yii::t('app', 'Designer Address'),
            'id_card' => Yii::t('app', 'Designer Id Card'),
            'image_idcard_a' => Yii::t('app', 'Designer Image Idcard A'),
            'image_idcard_b' => Yii::t('app', 'Designer Image Idcard B'),
            'image_bcard' => Yii::t('app', 'Designer Image Bcard'),
            'audit_state' => Yii::t('app', 'Designer Audit State'),
            'audit_uid' => Yii::t('app', 'Designer Audit Uid'),
            'audit_time' => Yii::t('app', 'Designer Audit Time'),
            'audit_memo' => Yii::t('app', 'Designer Audit Memo'),
            'province' => Yii::t('app', 'Province'),
            'city' => Yii::t('app', 'City'),
            'area' => Yii::t('app', 'Area'),
            'imageFile_idcard_a' => Yii::t('app', 'Designer Image Idcard A'),
            'imageFile_idcard_b' => Yii::t('app', 'Designer Image Idcard B'),
            'imageFile_bcard' => Yii::t('app', 'Designer Image Bcard'),
            'invite_f' => Yii::t('app', 'Invite F'),
            'user_type' => Yii::t('user', 'User Type'),
            'user_type_class' => Yii::t('app', 'User Level'),
            'time0.start_time' => '有效期',
        ];
    }

    public function getAdminName()
    {
        return $this->hasOne(AdminInfo::className(), ['id' => 'audit_uid']);//显示小图
    }

    //运营商的用户信息
    public static function infoByAddressAndType($address)
    {
        return self::find()->where("user_info.user_type=5 AND address='{$address}'")->joinWith(['userinfo'])->One();
    }
}
